<?php

Yii::import('application.modules.menu.utililies.menuService');
Yii::import('application.modules.user.models.User');

class OrdersController extends ControllerBase {

    public function init() {
        parent::init();
        $this->defaultAction = 'admin';
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Orders;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Orders'])) {
            $model->attributes = $_POST['Orders'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->orderid));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Orders'])) {
            $model->attributes = $_POST['Orders'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->orderid));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionView($id) {
        $orderDetail = Orderdetail::model()->findAll(array(
            'select' => 't.*, drinkname, count(t.drinkid) as total',
            'join' => 'JOIN drink ON drink.drinkid = t.drinkid',
            'condition' => 't.orderid = :orderid',
            'params' => array(
                ':orderid' => intval($id),
            ),
            'group' => 't.drinkid, syruplist, materiallist',
                ));

        $order = Orders::model()->find(array(
            'condition' => 'orderid = :orderid',
            'params' => array(
                ':orderid' => intval($id),
            )
                ));

        $this->render('view', array(
            'orderDetail' => $orderDetail,
            'order' => $order,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Orders');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Orders('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Orders']))
            $model->attributes = $_GET['Orders'];

        $this->render('admin', array(
            'model' => $model,
            'amountCoffees' => '3'
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Orders::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'orders-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionOrderStatistics() {
        $orders = Orders::model()->findAll();
        $orderDetails = Orderdetail::model()->findAll();

        $this->render('orderStatistics', array(
            'orders' => $orders,
            'orderDetails' => $orderDetails
        ));
    }

    public function actionStatisticsCupsOfCoffee() {
        $orders = Orders::model();

        //get statistics option
        $statisticsOption = isset($_POST['statistics_options']) ? $_POST['statistics_options'] : 'week';

        $criteria = new CDbCriteria();
        $criteria->select = "*";

        $amounts = 0;
        if ((isset($_POST['fromDate']) || isset($_POST['toDate'])) && ($_POST['toDate'] != '' && $_POST['fromDate'] != '')) {
            $fromDate = Util::foramtInputDate($_POST['fromDate']);
            $toDate = Util::foramtInputDate($_POST['toDate']);
            $criteria->condition = 'orderdate between ' . strtotime($fromDate) . " AND " . strtotime($toDate);
        } else if (isset($_POST['fromDate']) && $_POST['fromDate'] != '') {  //get cups beteen current ween, began in Monday ended by Sunday
            $fromDate = Util::foramtInputDate($_POST['fromDate']);
            $toDate = Util::foramtInputDate($_POST['toDate']);
            $week = date('W', strtotime($fromDate));
            $d = Util::getDaysInWeek($week, date('Y', time()));

            if ($statisticsOption == 'week') {
                $criteria->condition = 'orderdate between ' . ($d[0] + 86399) . ' AND ' . ($d[6] + 86399);
            } else if ($statisticsOption == 'day') {
                $criteria->condition = 'orderdate between ' . $d[(date('N', time()) - 1)] . ' AND ' . ($d[(date('N', time()) - 1)] + 84399);
            } else if ($statisticsOption == 'month') {
                $first_minute = mktime(0, 0, 0, date('m', strtotime($fromDate)), 1);
                $last_minute = mktime(23, 59, 0, date('m', strtotime($fromDate)), date('t', $first_minute));

                $criteria->condition = 'orderdate between ' . $first_minute . ' AND ' . $last_minute;
            } else if ($statisticsOption == 'year') {
                $first_minute = mktime(0, 0, 0, 1, 1, date('Y', strtotime($fromDate)));
                $last_minute = mktime(23, 59, 59, 12, 31, date('Y', strtotime($fromDate)));

                $criteria->condition = 'orderdate between ' . $first_minute . ' AND ' . $last_minute;
            }
        }

        $this->render('orderStatistics', array(
            'orders' => $orders->findAll($criteria),
            'statisticsOption' => $statisticsOption,
            'fromDate' => strtotime($fromDate),
            'toDate' => strtotime($toDate),
            'user' => $_POST['user'],
        ));
    }

    public function actionSyncOrders($syncOrderFileName) {
//        $orders = CJSON::decode($this->actionGenerateOrder());
//        $syncOrderFileName = $_GET['order'];
//        $ordersList = Yii::getPathOfAlias('webroot') . "/uploads/orders/orderList.txt";
        $ordersList = Yii::getPathOfAlias('webroot') . "/uploads/orders/".$syncOrderFileName.".txt";
		//var_dump(file_exists($ordersList));
        if (file_exists($ordersList)) {
            $f = fopen($ordersList, 'r');
            $orders = file_get_contents($ordersList);
			$data = explode("\n", $orders);
			$i=0;
			$totalMateiralList = 0;
			$totalSyrupList = 0;
			
			foreach ($data as $key => $val){				
				if (0==$i){
					$lineData = explode(":", $val);					
					$orderid = $lineData[0];
					$orderTable = $lineData[2];
					$orderUser = $lineData[3];
					$orderSyn = $lineData[4];					
				}else if (1==$i){				
					$orderDate = $val;
					//echo $orderid.":".$orderid.":".$orderTable.":".$orderUser.":".$orderSyn.":".$orderDate."<br/>";
					//echo "insert into orders values(".$orderid.",".$orderDate.",".$orderUser.",".$orderSyn.",".$orderTable.")<br/>";
					$order = new Orders('insert');
					$order->orderid = $orderid;
					$order->ordertable = $orderTable;
					$order->userid = $orderUser;
					$order->synced = $orderSyn;
					$order->orderdate = intval($orderDate);
					$order->save();
				}else if (2==$i){
					$listDrink = explode(",", $val);
				}else if (3==$i){
					$materialList = explode(",", $val);
					$ml = array_count_values($listDrink);
					foreach ($ml as $k => $v)
						$totalMateiralList += $v;
				}else if (4==$i){
					$materialQuantity = explode(",", $val);		
				}else if (5==$i){
					$syrupList = explode(",", $val);
				}else if (6==$i){
					$syrupQuantity = explode(",", $val);
				}else if (7==$i){
					$note = explode("{:}", $val);
					$orderDetailCount = array_count_values($listDrink);
					$y=0;
					foreach ($orderDetailCount as $k => $v){					
						$orderDetail = new Orderdetail('insert');
						$orderDetail->orderid = $orderid;
						$orderDetail->drinkid = $k;
						$tempMeterialArray = array();
						$tempSyrupArray = array();
						$tempNoteArray = array();
						$a = null;
						for($x=0; $x<$v; $x++){	// x is index element of materialList array	
							$materialListTemp = array(
								$materialList[$y] => $materialQuantity[$y],
							);		
							$syrupListTemp = array(
								$syrupList[$y] => $syrupQuantity[$y],
							);
							$noteTemp = array(
								$note[$y++],
							);
							array_push($tempMeterialArray, $materialListTemp);
							array_push($tempSyrupArray,$syrupListTemp);
							array_push($tempNoteArray, $noteTemp);
						}
						$orderDetail->materiallist = CJSON::encode($tempMeterialArray);
						$orderDetail->syruplist = CJSON::encode($tempSyrupArray);						
						$orderDetail->note = CJSON::encode($tempNoteArray);
						$orderDetail->save();						
						//if synced order, update order syced status
						$order->synced = 1;
						$order->updateByPK($orderid, array('synced' => 1));
						//echo '<pre>'; print_r($orderDetail->attributes); echo '</pre>';						
					}
					$totalMateiralList=0;
				}
				
				$i++;
				if (8==$i) $i=0;
			}			
            echo  CJSON::encode(array('sync order' => true));
        }else
            echo CJSON::encode(array('sync order' => false));
    }

    public function actionGenerateOrder() {
        $orders = Orders::model()->findAll();
		$list = null;
		$orderDetails = new Orderdetail;
				
		foreach ($orders as $order => $valueOrder){
			$orderDetails = Orderdetail::model()->findAll(array(
				'select' => 'orderid, GROUP_CONCAT(CAST(drinkid AS CHAR)) AS drinkid, GROUP_CONCAT(materiallist SEPARATOR "::") AS materiallist,  GROUP_CONCAT(syruplist SEPARATOR "::") AS syruplist, GROUP_CONCAT(note) AS note',
				'condition' => 'orderid = :id',
				'params' => array(
					':id' => $valueOrder->orderid,
				),			
			));
			
			foreach ($orderDetails as $detail => $val){				
				$list .= $valueOrder->orderid.":".$val->orderid.":".(is_null($valueOrder->ordertable) ? "0" : $valueOrder->ordertable) .":".$valueOrder->userid.":".$valueOrder->synced."<br/>";
				$list .= $valueOrder->orderdate."<br/>";
				$list .= $val->drinkid."<br/>";
				
				//indicate material id and material quantity
				echo $val->materiallist;
				$materialListArray = explode("::", $val->materiallist);
				$countMaterial = count($materialListArray);
				for($i=0; $i<$countMaterial; $i++){
					$material = $materialListArray[$i];
					$listMaterial = CJSON::decode($material);
					
				
					foreach ($listMaterial as $key => $value){
						$listMaterial_ .= $key.",";
						$listMaterialQuantity_ .= $value.",";	
						$drinkid_ .= $val->drinkid.",";						
					}
					echo $drinkid_;
					unset($drinkid_);
				}
				
				$list .= $listMaterial_."<br/>";
				$list .= $listMaterialQuantity_."<br/>";
				
				//indicate syrup id and syrup quantity
				$syrupListArray = explode("::", $val->syruplist);
				$countSyrup = count($syrupListArray);
				for($i=0; $i<$countSyrup; $i++){
					$syrup = $syrupListArray[$i];
					$listSyrup = CJSON::decode($syrup);
					
					foreach ($listSyrup as $key => $value){
						$listSyrup_ .= $key.",";
						$listSyrupQuantity_ .= $value.",";
					}
				}
				$list .= $listSyrup_."<br/>";
					$list .= $listSyrupQuantity_."<br/>";
				$list .= $val->note."note<br/>";
				
				$materialListArray = explode("::", $val->materiallist);				
			}
		}
		echo '<pre>';print_r($list); echo '</pre>';
    }

    public function actionTriggerSyncOrder($url = null){
        /*$order = isset($_GET['orderFileName']) ? $_GET['orderFileName'] : null;
        if (!is_null($order)){
            if (file_exists(Yii::getPathOfAlias('webroot')."/uploads/orders/".$order.".txt"))
                $this->actionSyncOrders($order.".txt");
            else{
                echo CJSON::encode(array('sync order' => false));
				exit(0);
			}
        }
        else{
            echo CJSON::encode(array('sync order' => false));
			exit(0);
		}*/
                $url = "dl.dropbox.com/u/12608736/How%20to%20use%20the%20Public%20folder.rtf";
//                
//                var_dump($url);
		var_dump(urlencode($url));
                var_dump($url);
//		echo "<br/>";
//		var_dump(htmlspecialchars("http://dl.dropbox.com/u/12608736/How%20to%20use%20the%20Public%20folder.rtf"));
//		echo "<br/>";
//		var_dump(htmlentities($url));
                echo ($url);
		//var_dump($this->is_available($url));
		/*if ($url !== null && $this->is_available($url)){
			$orderFileName = time();
			$downloaded = $this->downloadOrderFile($url, Yii::getPathOfAlias('webroot')."/uploads/orders/".$orderFileName.".txt");
			if ($downloaded){
				$this->actionSyncOrders($orderFileName.".txt");
			}else{
				echo CJSON::encode(array('sync order' => false));
				exit(0);
			}
		}else{
			echo CJSON::encode(array('sync order' => false));
			exit(0);
		}	*/	
    }
	
	public function is_available($url, $timeout = 30) {
		$ch = curl_init(); // get cURL handle
		// set cURL options
		$opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
			CURLOPT_URL => $url, // set URL
			CURLOPT_NOBODY => true, // do a HEAD request only
			CURLOPT_TIMEOUT => $timeout);   // set timeout
		curl_setopt_array($ch, $opts);

		curl_exec($ch); // do it!

		$retval = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200; // check if HTTP OK

		curl_close($ch); // close handle

		return $retval;
	}
	
	//download order.txt file from dropbox server with public share option
	private function downloadOrderFile($url, $path){
		$newfname = $path;
		//load public file link
		$file = fopen ($url, "rb");
		  
		if ($file) {
			//create file which save in server for sync order proccess
			$newf = fopen ($newfname, "wb");

			if ($newf)
				//write data into the file which was created
				while(!feof($file)) {
					fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
				}
		}

		//check public file 
		if ($file) 
			fclose($file);
		
		//check new order file on server
		if ($newf) {
			fclose($newf);
			return true;
		}else
			return false;
	}
	
	
	public function actionUploadOrder(){	
		if (isset($_FILES['orderfile'])){
			$upload = CUploadedFile::getInstanceByName("orderfile");			
			if ($upload->saveAs(Yii::getPathOfAlias('webroot') . "/uploads/orders/" . $upload->getName()))
				echo  CJSON::encode(array('upload order data' => true));
			else
				echo  CJSON::encode(array('upload order data' => false));
		}else{
			$this->render("uploadOrder");
		}
	}

    public function beforeAction($action) {
        parent::beforeAction($action);
        if (Yii::app()->user->id === null)
            $this->redirect(Yii::app()->createUrl('site/login'));
        return true;
        $this->redirect(Yii::app()->createUrl('site/login'));
    }
}